﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

using System;
using Tesla.Core;
using Tesla.Graphics.Implementation;
using Tesla.Math;

namespace Tesla.Graphics {
    /// <summary>
    /// BlendState object that controls how pixels are blended during rendering.
    /// </summary>
    public class BlendState : RenderState {
        private BlendStateImplementation _impl;
        private RenderStateKey _key;

        /// <summary>
        /// Gets a built-in state object for opaque blending, that is there is no blending and source data is overwritten by
        /// destination data. This is the default state.
        /// </summary>
        public static BlendState Opaque {
            get;
            internal set;
        }

        /// <summary>
        /// Gets a built-in state object for premultiplied alpha blending, that is blending source and destination
        /// data by using alpha where the color contains the alpha data.
        /// </summary>
        public static BlendState AlphaBlendPremultiplied {
            get;
            internal set;
        }

        /// <summary>
        /// Gets a built-in state object for additive blending, that is blending source and destination
        /// data without using alpha data.
        /// </summary>
        public static BlendState AdditiveBlend {
            get;
            internal set;
        }

        ///Gets a built-in state object for non-premultiplied alpha blending, that is blending source and destination 
        ///data by using alpha while assuming the color contains no alpha data.
        public static BlendState AlphaBlendNonPremultiplied {
            get;
            internal set;
        }

        /// <summary>
        /// Get if this render state has been bound to the pipeline.
        /// </summary>
        public override bool IsBound {
            get {
                return _impl.IsBound;
            }
        }

        /// <summary>
        /// Gets the <see cref="RenderStateKey"/> that is used to compare this state
        /// to another state.
        /// </summary>
        public override RenderStateKey RenderStateKey {
            get {
                if(!_impl.IsBound) {
                    return new RenderStateKey(GetHashCode(), StateType);
                }
                return _key;
            }
        }

        /// <summary>
        /// Get the enumeration describing this render state.
        /// </summary>
        public override RenderStateType StateType {
            get {
                return RenderStateType.BlendState;
            }
        }

        /// <summary>
        /// Gets the concrete implementation of this resource.
        /// </summary>
        public override GraphicsResourceImplementation Implementation {
            get {
                return _impl;
            }
        }

        /// <summary>
        /// Gets or sets the function used when blending alpha values. The default is
        /// <see cref="BlendFunction.Add"/>.
        /// </summary>
        public BlendFunction AlphaBlendFunction {
            get {
                return _impl.AlphaBlendFunction;
            }
            set {
                _impl.AlphaBlendFunction = value;
            }
        }

        /// <summary>
        /// Gets or sets the blend factor for the source alpha value. The default is
        /// <see cref="Blend.One"/>.
        /// </summary>
        public Blend AlphaSourceBlend {
            get {
                return _impl.AlphaSourceBlend;
            }
            set {
                _impl.AlphaSourceBlend = value;
            }
        }

        /// <summary>
        /// Gets or sets the blend factor for the destination alpha value. The default
        /// is <see cref="Blend.One"/>.
        /// </summary>
        public Blend AlphaDestinationBlend {
            get {
                return _impl.AlphaDestinationBlend;
            }
            set {
                _impl.AlphaDestinationBlend = value;
            }
        }

        /// <summary>
        /// Gets or sets the function used for blending color values. The default value 
        /// is <see cref="BlendFunction.Add"/>.
        /// </summary>
        public BlendFunction ColorBlendFunction {
            get {
                return _impl.ColorBlendFunction;
            }
            set {
                _impl.ColorBlendFunction = value;
            }
        }

        /// <summary>
        /// Gets or sets the blend factor for the source color. The default value
        /// is <see cref="Blend.One"/>.
        /// </summary>
        public Blend ColorSourceBlend {
            get {
                return _impl.ColorSourceBlend;
            }
            set {
                _impl.ColorSourceBlend = value;
            }
        }

        /// <summary>
        /// Gets or sets the blend factor for the destination color.The default value
        /// is <see cref="Blend.One"/>.
        /// </summary>
        public Blend ColorDestinationBlend {
            get {
                return _impl.ColorDestinationBlend;
            }
            set {
                _impl.ColorDestinationBlend = value;
            }
        }

        /// <summary>
        /// Gets or sets the four-component (RGBA) blend factor for alpha blending. The default value is
        /// <see cref="Color.White"/>.
        /// </summary>
        public Color BlendFactor {
            get {
                return _impl.BlendFactor;
            }
            set {
                _impl.BlendFactor = value;
            }
        }

        /// <summary>
        /// Gets or sets a mask that specifies which samples can be written to during multisampling.
        /// The default value is -1.
        /// </summary>
        public int MultiSampleMask {
            get {
                return _impl.MultiSampleMask;
            }
            set {
                _impl.MultiSampleMask = value;
            }
        }

        /// <summary>
        /// Gets the number of render targets that blending can be enabled for.
        /// </summary>
        public int BlendEnableCount {
            get {
                return _impl.BlendEnableCount;
            }
        }

        /// <summary>
        /// Gets the number of render targets that can have an independent write mask for.
        /// </summary>
        public int ColorWriteChannelsCount {
            get {
                return _impl.ColorWriteChannelsCount;
            }
        }

        /// <summary>
        /// Gets if blending is enabled for the render target index.
        /// </summary>
        /// <param name="index">Render target index</param>
        /// <returns>True if enabled, false otherwise</returns>
        public bool GetBlendEnable(int index) {
            return _impl.GetBlendEnable(index);
        }

        /// <summary>
        /// Sets if blending is enabled for the render target index.
        /// </summary>
        /// <param name="index">Render target index</param>
        /// <param name="enable">True if enabled, false if not</param>
        public void SetBlendEnable(int index, bool enable) {
            _impl.SetBlendEnable(index, enable);
        }

        /// <summary>
        /// Gets the write mask used by the render target specified by its index.
        /// </summary>
        /// <param name="index">Render target index</param>
        /// <returns>Write mask</returns>
        public ColorWriteChannels GetWriteChannels(int index) {
            return _impl.GetWriteChannels(index);
        }

        /// <summary>
        /// Sets the write mask used by the render target specified by its index.
        /// </summary>
        /// <param name="index">Render target index</param>
        /// <param name="mask">Color write mask to use</param>
        public void SetWriteChannels(int index, ColorWriteChannels mask) {
            _impl.SetWriteChannels(index, mask);
        }


        /// <summary>
        /// Creates a new instance of <see cref="BlendState"/> with default values.
        /// </summary>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying state implementation fails.</exception>
        public BlendState() {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateBlendStateImplementation();
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }

            SetDefaults();
        }

        /// <summary>
        /// Creates a new instance of <see cref="BlendState"/> with default values.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the render system is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying state implementation fails.</exception>
        public BlendState(IRenderSystemProvider renderSystem) {
            if(renderSystem == null) {
                Dispose();
                throw new ArgumentNullException("renderSystem", "Render system cannot be null.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateBlendStateImplementation();
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }

            SetDefaults();
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="BlendState"/> is reclaimed by garbage collection.
        /// </summary>
        ~BlendState() {
            Dispose(false);
        }

        private void SetDefaults() {
            //Set defaults
            _impl.AlphaBlendFunction = BlendFunction.Add;
            _impl.AlphaSourceBlend = Blend.One;
            _impl.AlphaDestinationBlend = Blend.Zero;

            _impl.ColorBlendFunction = BlendFunction.Add;
            _impl.ColorSourceBlend = Blend.One;
            _impl.ColorDestinationBlend = Blend.Zero;

            _impl.BlendFactor = Color.White;
            _impl.MultiSampleMask = int.MaxValue;

            int numWriteMasks = _impl.ColorWriteChannelsCount;
            int numEnables = _impl.BlendEnableCount;

            for(int i = 0; i < numWriteMasks; i++) {
                _impl.SetWriteChannels(i, ColorWriteChannels.All);
            }

            //Set first to true, since if we're creating a blend state most likely we want to blend, right?
            _impl.SetBlendEnable(0, true);
            for(int i = 1; i < numEnables; i++) {
                _impl.SetBlendEnable(i, false);
            }
        }

        /// <summary>
        /// Binds the render state to the graphics pipeline. This is automatically called the first time the
        /// renderstate is applied or manually called to create the underlying implementation early.
        /// </summary>
        public override void BindRenderState() {
            if(!IsBound) {
                _impl.BindBlendState();
                _key = new RenderStateKey(GetHashCode(), StateType);
            }
        }

        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        /// <returns>A hash code for this instance.</returns>
        public override int GetHashCode() {
            int hash = StateType.GetHashCode();

            for(int i = 0; i < _impl.BlendEnableCount; i++) {
                hash = ((hash << 2) - hash) +((_impl.GetBlendEnable(i)) ? 1 : 0);
            }

            for(int i = 0; i < _impl.ColorWriteChannelsCount; i++) {
                hash = ((hash << 2) - hash) +_impl.GetWriteChannels(i).GetHashCode();
            }

            hash = ((hash << 2) - hash) + _impl.AlphaBlendFunction.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.AlphaSourceBlend.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.AlphaDestinationBlend.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.ColorBlendFunction.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.ColorSourceBlend.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.ColorDestinationBlend.GetHashCode();
            hash = ((hash << 2) - hash) + (_impl.MultiSampleMask % int.MaxValue);
            return hash;
        }

        /// <summary>
        /// Serializes the object and writes it to the output.
        /// </summary>
        /// <param name="output">Savable Output</param>
        public override void Write(Content.ISavableWriter output) {
            output.WriteEnum<BlendFunction>("AlphaBlendFunction", _impl.AlphaBlendFunction);
            output.WriteEnum<Blend>("AlphaSourceBlend", _impl.AlphaSourceBlend);
            output.WriteEnum<Blend>("AlphaDestinationBlend", _impl.AlphaDestinationBlend);

            output.WriteEnum<BlendFunction>("ColorBlendFunction", _impl.ColorBlendFunction);
            output.WriteEnum<Blend>("ColorSourceBlend", _impl.ColorSourceBlend);
            output.WriteEnum<Blend>("ColorDestinationBlend", _impl.ColorDestinationBlend);

            output.Write("BlendFactor", _impl.BlendFactor);
            output.Write("MultiSampleMask", _impl.MultiSampleMask);

            int numBlends = _impl.BlendEnableCount;
            int numMasks = _impl.ColorWriteChannelsCount;

            output.Write("BlendEnableCount", numBlends);
            for(int i = 0; i < numBlends; i++) {
                output.Write(string.Format("BlendEnable{0}", i.ToString()), _impl.GetBlendEnable(i));
            }

            output.Write("ColorWriteChannelsCount", numMasks);
            for(int i = 0; i < numMasks; i++) {
                output.Write(string.Format("ColorWriteMask{0}", i.ToString()), (int)_impl.GetWriteChannels(i));
            }
        }

        /// <summary>
        /// Deserializes the object and populates it from the input.
        /// </summary>
        /// <param name="input">Savable input</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying state implementation fails or the render
        /// system is not set.</exception>
        public override void Read(Content.ISavableReader input) {
            IRenderSystemProvider renderSystem = input.RenderSystem;
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;
            try {
                _impl = renderSystem.CreateBlendStateImplementation();
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }

            _impl.AlphaBlendFunction = input.ReadEnum<BlendFunction>();
            _impl.AlphaSourceBlend = input.ReadEnum<Blend>();
            _impl.AlphaDestinationBlend = input.ReadEnum<Blend>();

            _impl.ColorBlendFunction = input.ReadEnum<BlendFunction>();
            _impl.ColorSourceBlend = input.ReadEnum<Blend>();
            _impl.ColorDestinationBlend = input.ReadEnum<Blend>();

            _impl.BlendFactor = input.ReadColor();
            _impl.MultiSampleMask = input.ReadInt();

            int numBlends = _impl.BlendEnableCount;
            int numMasks = _impl.ColorWriteChannelsCount;

            //Need to be careful here, this can change across different implementations. Just read in what we can and move on.
            int readNumBlends = input.ReadInt();
            for(int i = 0; i < numBlends; i++) {
                _impl.SetBlendEnable(i, input.ReadBoolean());
            }

            int readNumMasks = input.ReadInt();
            for(int i = 0; i < numMasks; i++) {
                _impl.SetWriteChannels(i, (ColorWriteChannels) input.ReadInt());
            }
        }
    }
}
